<template>
  <template v-if="chooseValue === '列表模式'">
    <n-space
      vertical
      size="large"
    >
      <n-layout-content content-style="padding: 24px;">
        <n-button
          @click="addNew()"
          type="primary"
          dashed
          >添加记录</n-button
        >
        <n-data-table
          v-show="!showEmpty"
          :columns="columns"
          :data="tableData"
          :pagination="false"
          :bordered="false"
          :id="'taskLogListDragTable'"
          :row-props="rowProps"
        />
        <n-data-table
          v-show="showEmpty"
          :columns="columns"
          :data="[]"
          :pagination="false"
          :bordered="false"
        />
      </n-layout-content>
      <n-dropdown
        placement="bottom-start"
        trigger="manual"
        :x="xRef"
        :y="yRef"
        :options="options"
        :show="showDropdownRef"
        :on-clickoutside="onClickoutside"
        @select="handleSelect"
      />
    </n-space>
  </template>
  <template v-if="chooseValue === '饼图'">
    <TimePie
      :data="timePieData"
      :key="timestamp"
      :type="1"
    ></TimePie>
  </template>
  <TaskLogEditDrawer v-model="editSettings"></TaskLogEditDrawer>
  <TaskLogDelModal v-model="editSettings"></TaskLogDelModal>
</template>
<script lang="ts" setup>
import TimePie from "@/components/common/TimePie.vue";
import TaskLogDelModal from "@/components/operation/taskLogList/taskLogListBtn/TaskLogDelModal.vue";
import TaskLogEditDrawer from "@/components/operation/taskLogList/taskLogListBtn/TaskLogEditDrawer.vue";
import { RemoveMethods } from "@/types/remove-methods";
import { TaskData } from "@model/TaskList";
import { TaskLogData } from "@model/TaskLogMap";
import UseCacheTaskLog from "@pinias/UseCacheTaskLog";
import pinia from "@pinias/pinia";
import { DateTimeStr, getstartOfDay, getEndOfDay } from "@utils/DateUtils";
import * as DateUtils from "@utils/DateUtils";
import { NButton, NDataTable, NLayoutContent, NSpace } from "naive-ui";
import { reactive, h, onMounted } from "vue";
import { watch, ref } from "vue";

// 全局数据
const { getCacheTaskLogMap } = UseCacheTaskLog(pinia);
const cacheTaskLogMap = getCacheTaskLogMap();
// 当前页面数据
const props = defineProps(["timestamp", "chooseValue"]);
const showEmpty = ref(false);
const editSettings = reactive<{
  toEdit: boolean;
  toDelete: boolean;
  toDealRowId: string | undefined;
  toRecord: boolean;
}>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
  toRecord: false,
});
class RowData {
  id: string;
  type: string;
  taskId: number | undefined;
  fieldName: string | undefined;
  stageName: string | undefined;
  taskName: string | undefined;
  startTime: string;
  endTime: string;
  takeTime: string;
  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({
      id: "",
      type: "",
      taskId: 0,
      startTime: "",
      fieldName: "",
      stageName: "",
      taskName: "",
      endTime: "",
      takeTime: "",
    });
  }
}
// 表格
const getTableData = async () => {
  const result = [];
  // console.log(props.timestamp)
  const taskLogMap = await cacheTaskLogMap.getTaskLogMap(props.timestamp);
  const dateTimeStr = new DateTimeStr(props.timestamp);
  const dayKey = dateTimeStr.getDayInfo();
  const list = taskLogMap.everyDayLogMap.get(dayKey);
  // console.log(taskLogMap.everyDayLogMap,dayKey)
  if (list !== undefined) {
    const map = taskLogMap.taskLogMap;
    // console.log("getTableData",map)
    for (let i = 0; i < list.length; i++) {
      const id = list[i];
      const oldDdata = map.get(id);
      if (oldDdata !== undefined) {
        // console.log((task["1"]["已完成"].length+task["2"]["已完成"].length))
        const oldFatherId = await TaskLogData.getFatherId(oldDdata.type, oldDdata.taskId);
        let fieldName = "";
        let stageName = "";
        let taskName = "";
        if (oldFatherId.length > 2) {
          fieldName = oldFatherId[2]?.name;
          stageName = oldFatherId[1]?.name;
          taskName = oldFatherId[0]?.name;
        } else {
          fieldName = oldFatherId[1]?.name;
          taskName = oldFatherId[0]?.name;
        }
        result.push(
          new RowData({
            id: oldDdata.id,
            type: TaskData.getTypeStr(oldDdata.type),
            taskId: oldDdata.taskId,
            fieldName: fieldName,
            stageName: stageName,
            taskName: taskName,
            startTime: DateUtils.timestampToDateTime(oldDdata.startTime),
            endTime: DateUtils.timestampToDateTime(oldDdata.endTime),
            takeTime: DateUtils.changeTimeUnit(oldDdata.endTime - oldDdata.startTime),
          }),
        );
      }
    }
  }
  if (result.length == 0) {
    result.push(RowData.getNullModel());
    showEmpty.value = true;
  } else showEmpty.value = false;
  return result;
};
// const tableData = ref(await getTableData());
const tableData = ref(new Array<RowData>());

const getTimePieData = () => {
  let lastStartTime = getstartOfDay(props.timestamp);
  const timePie = [];
  for (const tableDatum of tableData.value) {
    if (tableDatum.taskId !== 0) {
      const interVal = DateUtils.timeToTimestamp(tableDatum.startTime) - lastStartTime;
      if (interVal > 0) timePie.push({ value: interVal, name: "未记录" });
      timePie.push({
        value: DateUtils.timeToTimestamp(tableDatum.endTime) - DateUtils.timeToTimestamp(tableDatum.startTime),
        name: tableDatum.taskName,
      });
      lastStartTime = DateUtils.timeToTimestamp(tableDatum.endTime);
    }
  }
  timePie.push({ value: getEndOfDay(props.timestamp) - lastStartTime, name: "未记录" });
  // console.log("timePie",timePie,tableData.value)
  timePieData.value = timePie;
};
const timePieData = ref(new Array<{ value: number; name: string | undefined }>());

// console.log(tableData)
const watchTableData = async () => {
  // editSettings.state = taskState.value;
  // console.log(tableData);
  tableData.value = await getTableData();
  getTimePieData();
};
// watch(setting, watchTableData);
watch(cacheTaskLogMap, watchTableData);
onMounted(async () => {
  await watchTableData();
});

// 渲染表头
const play = (row: RowData) => {
  // message.info(`Play ${row.title}`);
  console.log(row);
};
const createColumns = () => {
  return [
    {
      title: "id",
      key: "id",
    },
    {
      title: "类型",
      key: "type",
    },
    {
      title: "领域",
      key: "fieldName",
    },
    {
      title: "阶段",
      key: "stageName",
    },
    {
      title: "任务",
      key: "taskName",
    },
    {
      title: "所花时间",
      key: "takeTime",
    },
    {
      title: "开始时间",
      key: "startTime",
    },
    {
      title: "结束时间",
      key: "endTime",
    },
    {
      title: "Action",
      key: "actions",
      render(row: RowData) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            id: "handle-drag",
            onClick: () => play(row),
          },
          { default: () => "Play" },
        );
      },
    },
  ];
};
const columns = createColumns();

// 右键菜单
const rowProps = (row: RowData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      editSettings.toDealRowId = row.id;
    },
  };
};
const options = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
const handleSelect = (key: string, node: string) => {
  console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
  }
  if (key == "delete") {
    editSettings.toDelete = true;
  }
};

const addNew = () => {
  editSettings.toEdit = true;
  editSettings.toDealRowId = undefined;
  // console.log(editSettings);
};
</script>
